from typing import Optional
import tkinter as tk
from tkinter import filedialog

import cv2
import numpy as np
from numpy import ndarray as mat


class GaussianSelectorTool:
    def __init__(self, windows_width: int = 720, windows_height: int = 640, windows_name: str = "Gaussian Selector Tool"):
        self.__windows_width: int = windows_width
        self.__windows_height: int = windows_height
        self.__windows_name: str = windows_name
        self.__img_hsv: Optional[mat] = None

    def run_bgr(self, img_bgr):
        img_hsv = cv2.cvtColor(img_bgr, cv2.COLOR_BGR2HSV)
        self.run_hsv(img_bgr)

    def run_hsv(self, img_bgr):
        self.__img_bgr = img_bgr
        cv2.namedWindow(self.__windows_name, cv2.WINDOW_NORMAL)
        debug_resize_times = 0.6
        cv2.resizeWindow(self.__windows_name, np.int_(self.__windows_width * debug_resize_times),
                         np.int_(self.__windows_height * debug_resize_times * 1.5))
        cv2.createTrackbar('Gaussian-ksize1', self.__windows_name, 1, 20, self.__cv_select_callback)
        cv2.createTrackbar('Gaussian-ksize2', self.__windows_name, 1, 20, self.__cv_select_callback)
        cv2.createTrackbar('average_diff', self.__windows_name, 1, 20, self.__cv_select_callback)
        ksize1, ksize2, average_diff = 1, 1, 1

        while True:
            ksize1 = cv2.getTrackbarPos('Gaussian-ksize1', self.__windows_name)
            ksize2 = cv2.getTrackbarPos('Gaussian-ksize2', self.__windows_name)
            average_diff = cv2.getTrackbarPos('average_diff', self.__windows_name)
            if ksize1!=0 and ksize2!=0 and ksize1%2!=0 and ksize2%2!=0:
                img_blur = cv2.GaussianBlur(img_bgr, (ksize1, ksize2), average_diff)
                cv2.imshow("blur", img_blur)
            # range_min = np.array([min_h, min_s, min_v])
            # range_max = np.array([max_h, max_s, max_v])
            # print(f"Range [H, S, V]: MIN - [{min_h}, {min_s}, {min_v}], MAX - [{max_h}, {max_s}, {max_v}]")

            # img_hsv_debug = cv2.inRange(self.__img_hsv, range_min, range_max)
            cv2.imshow(self.__windows_name, img_bgr)

            key = cv2.waitKey(10)
            if key & 0xFF == ord('q'):
                cv2.destroyWindow(self.__windows_name)
                break

        return ksize1, ksize2, average_diff

    @staticmethod
    def __cv_select_callback(value: int):
        pass


if __name__ == '__main__':
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.askopenfilename()
    print("Selected file:", file_path)
    tool = GaussianSelectorTool()
    tool.run_bgr(cv2.imread(file_path))
